package com.lemon.smartsafety.ui.activity.notice;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.common.MultiSelectItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.notice.NoticeRefreshEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.NoticeServices;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.activity.common.RoleActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.app.ViewViladateUtils;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.tagview.OnTagDeleteListener;
import com.lemon.smartsafety.view.tagview.Tag;
import com.lemon.smartsafety.view.tagview.TagView;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/8.
 */
public class NoticePropActivity extends PhotoSelectBaseActivity {

    private LoggerHelper loggerHelper = new LoggerHelper(NoticePropActivity.class);

    @Bind(R.id.metNoticeTitle)
    MaterialEditText metNoticeTitle;
    @Bind(R.id.metContent)
    MaterialEditText metContent;
    @Bind(R.id.tagIndustry)
    TagView          tagIndustry;
    @Bind(R.id.tagRole)
    TagView          tagRole;
    @Bind(R.id.tagAddressBook)
    TagView          tagAddressBook;


    private boolean isEdit = false;


    private List<SelectDataI> selectRoles       = new ArrayList<>();
    private List<SelectDataI> selectIndustry    = new ArrayList<>();
    private List<SelectDataI> selectAddressBook = new ArrayList<>();


    @Override
    protected void initTitle() {
        setBarTitle("安全公告");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(NoticePropActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_notice_prop;
    }


    @Override
    protected void initViews() {
        super.initViews();

        tagRole.setOnTagDeleteListener(new OnTagDeleteListener() {
            @Override
            public void onTagDeleted(Tag tag, int position) {
                selectRoles.remove(position);
            }
        });


        tagIndustry.setOnTagDeleteListener(new OnTagDeleteListener() {
            @Override
            public void onTagDeleted(Tag tag, int position) {
                selectIndustry.remove(position);
            }
        });


        tagAddressBook.setOnTagDeleteListener(new OnTagDeleteListener() {
            @Override
            public void onTagDeleted(Tag tag, int position) {
                selectAddressBook.remove(position);
            }
        });
    }

    @OnClick({R.id.tagIndustry})
    public void tagIndustryClick(View view) {
        UIHelper.showIndustryActivity(this, selectIndustry);

    }

    @OnClick({R.id.tagRole})
    public void tagRoleClick(View view) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(BundleKey.IS_MULTI_SELECT, true);
        bundle.putSerializable(BundleKey.OLD_SELECT_VALUE_LIST, (Serializable) selectRoles);
        UIHelper.showActivity(this, bundle, RoleActivity.class);
    }


    @Subscribe
    public void onEventMainThread(MultiSelectItemEvent event) {
        List<SelectDataI> items = event.getData();
        if (event.getTag().equals(EventTag.TAG_ROLE)) {
            if (items != null && items.size() != 0) {
                selectRoles.clear();
                selectRoles.addAll(items);
                setTagView(tagRole, selectRoles);
            } else {
                selectRoles.clear();
                tagRole.removeAllTags();
            }
        } else if (event.getTag().equals(EventTag.TAG_INDUSTRY)) {
            if (items != null && items.size() != 0) {
                selectIndustry.clear();
                selectIndustry.addAll(items);
                setTagView(tagIndustry, selectIndustry, R.color.colorPrimary);
            } else {
                selectIndustry.clear();
                tagIndustry.removeAllTags();
            }
        } else if (event.getTag().equals(EventTag.TAG_ADDRESS_BOOK_SELECT)) {
            if (items != null && items.size() != 0) {
                selectAddressBook.clear();
                selectAddressBook.addAll(items);
                setTagView(tagAddressBook, selectAddressBook, R.color.green);
            } else {
                selectAddressBook.clear();
                tagAddressBook.removeAllTags();
            }
        }
    }


    @OnClick({R.id.tagAddressBook})
    public void tagAddressBookClick(View view) {
        UIHelper.showMultiAddressBookActivity(this, selectAddressBook);
    }

    @OnClick({R.id.btn_submit})
    public void submitClick(View view) {
        if (!validateForm()) {
            return;
        }
        getConfirmDialog("是否提交？", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doSubmitAction();
                }
            }
        }).show();
    }

    private boolean validateForm() {
        if (ViewViladateUtils.valueEmpty(metNoticeTitle)) {
            metNoticeTitle.setError("请填写公告标题");
            mHUDUtil.showErrorTip(metNoticeTitle.getError().toString());
            return false;
        }

        if (ViewViladateUtils.valueEmpty(metContent)) {
            metContent.setError("请填写公告内容");
            mHUDUtil.showErrorTip(metContent.getError().toString());
            return false;
        }
        return true;
    }

    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams("notice_info", "notice_id", "");
        params.put("_txtIdValues", "");
        params.put("notice_id", "");
        params.put("txtRecorderId", mSharedPreferencesHelper.getUserId(), Field.TYPE_STRING);
        params.put("txtRecordDate", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATETIME);
        params.put("txtTitle", metNoticeTitle.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtContent", metContent.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtSchTxt", metContent.getText().toString().trim(), Field.TYPE_STRING);
        //后来直接修改为默认发送
        params.put("chkStatus", "1", Field.TYPE_BOOLEAN);
        params.put("chkIsPublic", "1", Field.TYPE_BOOLEAN);

        String sIndus  = getListSplit(selectIndustry);
        String sRoles  = getListSplit(selectRoles);
        //String sGroups = getListSplit(selectAddressBook);


        if (sIndus.length() != 0) {
            params.put("selIndustryTypeIdsSelect", sIndus, Field.TYPE_STRING);
        }
        if (sRoles.length() != 0) {
            params.put("selUserType", sRoles, Field.TYPE_STRING);
        }
       /* if (sGroups.length() != 0) {
            params.put("selGroupIds", sGroups, Field.TYPE_STRING);
        }*/



        getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
            @Override
            public void onStart() {
                mHUDUtil.showHUD();
            }

            @Override
            public void onFinish(List<UploadFileItem> data) {
                if (data != null && data.size() != 0) {
                    params.put("files", mGson.toJson(data));
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        NoticeServices.init().saveAction(params, isEdit);
                    }
                });
            }
        });

    }


    /**
     * 处理所有的网络请求返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_NOTICE_ACTION == event.getTag()) {//隐患保存Action
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            NoticeRefreshEvent refreshEvent = new NoticeRefreshEvent();
                            AppService.getBus().post(refreshEvent);
                            AppManager.getAppManager().finishActivity(NoticePropActivity.this);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @Override
    public void evidencePlusEventHandler(String tag) {
        if (this.getClass().getName().equals(tag)) {
            showActionSheet(EvidenceActionSheetType.CAMERA_VOICE);
        }
    }



    @OnClick({R.id.btn_sent})
    public void sentAction(View view) {
        Bundle bundle = new Bundle();
        UIHelper.showActivity(NoticePropActivity.this, bundle, NoticeSentListActivity.class);
    }
}
